package com.yuanfengerp.inventorycheck.missioncheck.service.impl;

import com.yuanfengerp.inventorycheck.missioncheck.dao.IChecktaskDao;
import com.yuanfengerp.inventorycheck.missioncheck.model.Checktask;
import com.yuanfengerp.inventorycheck.missioncheck.service.IChecktaskService;
import com.yuanfengerp.publicUtil.Result;
import com.yuanfengerp.publicUtil.SnowflakeIdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ChecktaskServiceImpl implements IChecktaskService {
    @Autowired
    IChecktaskDao ictd;
    @Override
    public Result<List<Checktask>> selectTaskAll(Map<String, Object> params) {
        params.put("pagenum",((int) params.get("pagenum")-1) * (int) params.get("num"));
        List<Checktask> checktasks = ictd.selectTaskAll(params);
        if (checktasks.isEmpty())
            return Result.failure(400, "没有数据");
        return Result.success(checktasks, ictd.Count());
    }

    @Override
    public Result<List<Checktask>> selectTaskAndshopAll(String document_ID) {
        List<Checktask> checktasks = ictd.selectTaskAndshopAll(document_ID);
        if (!(checktasks.isEmpty()))
            return Result.success(checktasks);
        return Result.failure(400, "没有数据");
    }

    @Override
    @Transactional
    public Result<String> addTask(Checktask checktask) {
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0);
        checktask.setDocument_ID(idWorker.nextId());
        checktask.setEstablish_time(new Date(System.currentTimeMillis()));
        checktask.setOperation_time(new Date(System.currentTimeMillis()));
        checktask.getCheckproducts().forEach(checkproduct -> {
            checkproduct.setPm_id(checktask.getDocument_ID());
            checkproduct.setPm_category(checktask.getWarehouse_name());
        });
        int addtask = ictd.addtask(checktask);
        checktask.getCheckproducts().forEach(checkproduct -> {
            ictd.addcheckproduct(checkproduct);
        });
        if (addtask == 1)
            return Result.success("新增成功");
        return Result.failure(500,"新增失败");
    }

    @Override
    @Transactional
    public Result<String> deleteTask(String document_ID) {
        int deleteTask = ictd.deletetask(document_ID);
        int deletecheckproduct = ictd.deletecheckproduct(document_ID);
        if (deleteTask > 0 && deletecheckproduct > 0)
            return Result.success("删除成功");
        return Result.failure(500,"删除失败");
    }


}
